package middle

import (
	"entry_task/backend/src/brpc"
	"entry_task/backend/src/common"
	"entry_task/backend/src/vo"
	api "entry_task/entry_api/service"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func AuthorityFilter(c *gin.Context) {
	fmt.Println("---------自定义中间件-------")

	path := c.FullPath()
	if strings.Contains(path, "/open/") {
		c.Next()
		return
	}

	token := c.GetHeader(common.TOKEN_KEY)
	if token == "" {
		// 阻止调用后续的处理函数
		c.Abort()
		result := vo.Result{Code: vo.TokenInvalidCode, Message: "token为空"}
		c.JSON(http.StatusOK, result)
		return
	}
	// 通过 token从用户服务 获取用户信息
	userInfoClient := brpc.GetUserInfoClient()
	userInfo, _ := userInfoClient.GetByToken(c, &api.TokenMessage{Token: token})
	if userInfo == nil {
		c.Abort()
		result := vo.Result{Code: vo.TokenInvalidCode, Message: "token已失效,请从新登陆"}
		c.JSON(http.StatusOK, result)
		return
	}
	//utils.CheckErr(err) todo getByToken 返回值 err 明明是nil 但是到这里却不是nil
	c.Set(vo.CurrentUserKey, userInfo)

}

/**
获取当前登陆的用户
*/
func GetCurrentUser(c *gin.Context) *api.UserInfoResp {
	currUser, exists := c.Get(vo.CurrentUserKey)
	if !exists {
		return nil
	}
	userTo, ok := (currUser).(*api.UserInfoResp)
	if !ok {
		return nil
	}
	return userTo
}
